//
//  ChoiceController.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/2/5.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import Foundation
import SwiftProgressHUD

class ChoiceController: UITableViewController {
    
    var sign : String?
    @IBOutlet weak var paymentTypeLabel: UILabel!
    @IBOutlet weak var paymentMoneyLabel: UILabel!
    @IBOutlet weak var moneyTextField: UITextField!
    @IBOutlet weak var amountTypeLabel: UILabel!
    @IBOutlet weak var modeLabel: UILabel!
    
    @IBOutlet weak var weixinPayButton: UIButton!
    @IBOutlet weak var zhifubaoPayButton: UIButton!
    
    @IBOutlet weak var balanceButton: UIButton!
    @IBOutlet weak var confirmButton: UIButton!
    
    var shareId = "2"
    var orderId = ""
    var paymentMoney = "0.00"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if sign == "recharge" {
            
            self.title = "充值"
            
        } else {
            self.title = "订单支付"
            paymentTypeLabel.text = "订单总额（元）"
            modeLabel.text = "支付方式"
            confirmButton.setTitle("确认", for: .normal)
        }
        
        paymentMoneyLabel.text = paymentMoney
        
        NotificationCenter.default.addObserver(self, selector: #selector(alipayResult), name: NSNotification.Name(rawValue: "alipayResult"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(weixinpayResult), name: NSNotification.Name(rawValue: "weixinpayResult"), object: nil)
    }
    
    @objc func alipayResult(notification:NSNotification) {
        SwiftProgressHUD.showOnlyText("支付成功")
        navigationController?.popViewController(animated: true)
    }
    
    @objc func weixinpayResult(notification:NSNotification) {
        SwiftProgressHUD.showOnlyText("支付成功")
        navigationController?.popViewController(animated: true)
    }
    
    //确认
    @IBAction func confirmBanAction(_ sender: UIButton) {
        
        if sign == "recharge" {
            
            requestRecharge(shareId: shareId, body: "充值", totalFee: moneyTextField.text!)
        }else {
            requestpayOrder(shareId: shareId, orderId: orderId)
        }
        
    }
    
    //充值
    func requestRecharge(shareId:String,body:String,totalFee:String) -> Void {
        
        if totalFee.isEmpty||totalFee.hasPrefix("."){
            SwiftProgressHUD.showOnlyText("请输入合法金额")
            return
        }
        
        //要加密的数据
        let param = ["command":"recharge","token":UserTicketModel.sharedInstance.token,"uid":UserTicketModel.sharedInstance.uid,"appType":"4","totalFee":totalFee,"shareId":shareId,"app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Pay"], successed: { (resultDict) in
            
            if shareId=="1"{
                self.Alipay(sign: (resultDict["data"] as! String))
            }else {
                let data = resultDict["data"] as! [String:AnyObject]
                self.weixin(appid: data["appid"] as! String, partnerid: data["partnerid"] as! String, prepayid: data["prepayid"] as! String, timestamp: data["timestamp"] as! String, noncestr: data["noncestr"] as! String, package: data["package"] as! String, sign: data["sign"] as! String)
            }
            
        })
    }
    
    //订单支付
    func requestpayOrder(shareId:String,orderId:String) -> Void {
        
        //要加密的数据
        let param = ["command":"payOrder","token":UserTicketModel.sharedInstance.token,"uid":UserTicketModel.sharedInstance.uid,"shareId":shareId,"orderId":orderId]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Pay"], successed: { (resultDict) in
            
            if shareId=="1"{
                self.Alipay(sign: (resultDict["data"] as! String))
            }else if shareId=="2"{
                let data = resultDict["data"] as! [String:AnyObject]
                self.weixin(appid: data["appid"] as! String, partnerid: data["partnerid"] as! String, prepayid: data["prepayid"] as! String, timestamp: data["timestamp"] as! String, noncestr: data["noncestr"] as! String, package: data["package"] as! String, sign: data["sign"] as! String)
            }else {
                SwiftProgressHUD.showOnlyText((resultDict["msg"]) as! String)
                self.navigationController?.popViewController(animated: true)
            }
     
        })
    }
    
    func Alipay(sign:String)
        
    {
        AlipaySDK.defaultService().payOrder(sign, fromScheme: "newshaohuoAlipay") { (resultDic) in
        print("支付宝支付结果\(resultDic!)")
        }
        
    }
    
    func weixin(appid:String,partnerid:String,prepayid:String,timestamp:String,noncestr:String,package:String,sign:String) {
            //调起微信
            let req = PayReq()
            //应用的AppID(固定的)
            req.openID = appid
            //商户号(固定的)
            req.partnerId = partnerid
            //扩展字段(固定的)
            req.package = package
            //统一下单返回的预支付交易会话ID
            req.prepayId = prepayid
            //随机字符串
            req.nonceStr = noncestr
            //时间戳(10位)
            req.timeStamp = UInt32("\(timestamp)")!
            //签名
            req.sign = sign
            WXApi.send(req)
        
    }
}


extension ChoiceController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if sign==nil{
            if section == 0 {
                return 1
            }else {
                return 4
            }
        }else {
            if section==0 {
                return 2
            }
            return 3
        }
        
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if indexPath.section==1 {
            if indexPath.row==1 {
                
                weixinPayButton.isSelected = true
                zhifubaoPayButton.isSelected = false
                balanceButton.isSelected = false
                shareId = "2"
                
            }else if indexPath.row==2{
                
                zhifubaoPayButton.isSelected = true
                weixinPayButton.isSelected = false
                balanceButton.isSelected = false
                shareId = "1"
                
            }else {
                zhifubaoPayButton.isSelected = false
                weixinPayButton.isSelected = false
                balanceButton.isSelected = true
                shareId = "0"
            }
        }
    }
}
